# 将每个分类的数据，分别创建一个 sheet 页

import xlrd
from xlutils.copy import copy

def get_data():
    wb = xlrd.open_workbook('../02.py_excelFile/data01.xls')
    sh = wb.sheet_by_index(0)

    ''' all_data 的结构模式：
            {
                a: [{}, {}, {}]
                b: [{}, {}, {}]
                c: [{}, {}, {}]
            }
    '''
    all_data = {}
    for r in range(sh.nrows):
        d = {'type': sh.cell_value(r, 1), 'name': sh.cell_value(r, 2), 'count': sh.cell_value(r, 3), 'price': sh.cell_value(r, 4)}
        key = sh.cell_value(r, 0)
        if all_data.get(key):
            all_data[key].append(d)
        else:
            all_data[key] = [d]

    return all_data


def save(data):
    wb = xlrd.open_workbook('../02.py_excelFile/data01.xls')
    wb2 = copy(wb)
    for key in data.keys():
        temp_sheet = wb2.add_sheet(key)
        for i, d in enumerate(data.get(key)):
            temp_sheet.write(i, 0, d.get('type'))
            temp_sheet.write(i, 1, d.get('name'))
            temp_sheet.write(i, 2, d.get('count'))
            temp_sheet.write(i, 3, d.get('price'))

    wb2.save('../02.py_excelFile/data01-拆分表格.xls')


if __name__ == '__main__':
    data = get_data()
    save(data)


